package com.hctforgreen.greenservice.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.hctforgreen.greenservice.model.UserInfoEntity;

/**
 * User info 存储Util
 * 
 * @author Tallen Zhai
 * 
 */
public class UserInfoStoreUtil {

	/**
	 * 保存userInfo
	 * 
	 * @param activity
	 */
	public static void saveUserInfo(Activity activity,
			UserInfoEntity entity) {
		SharedPreferences sharedPreferences = activity.getSharedPreferences(
				HctConstants.USER_INFO_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		Editor editor = sharedPreferences.edit();

		String userInfo = userInfoEntity2UserInfoString(entity);
		editor.putString(HctConstants.USER_INFO_STORE_KEY_VALUE, userInfo);
		editor.commit();
	}

	private static String userInfoEntity2UserInfoString(
			UserInfoEntity entity) {
		String userInfo = "";
		userInfo = entity.userId + ";" + entity.userName + ";"
				+ entity.userDepart + ";" + entity.userAut;
		return userInfo;
	}

	/**
	 * 获取userInfo
	 * 
	 * @param activity
	 * @return
	 */
	public static UserInfoEntity getUserInfo(Activity activity) {
		SharedPreferences sharedPreferences = activity.getSharedPreferences(
				HctConstants.USER_INFO_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		String userInfo = sharedPreferences.getString(
				HctConstants.USER_INFO_STORE_KEY_VALUE, "");
		return userInfoString2UserInfoEntity(userInfo);
	}

	private static UserInfoEntity userInfoString2UserInfoEntity(String userInfo) {
		String[] strings = userInfo.split(";");
		UserInfoEntity entity = new UserInfoEntity();
		if (strings != null && strings.length == 4) {
			entity.userId = strings[0];
			entity.userName = strings[1];
			entity.userDepart = strings[2];
			entity.userAut = strings[3];
		}
		return entity;
	}
	/**
	 * 保存密码
	 * @param activity
	 * @param password
	 */
	public static void savePassword(Activity activity,
			String password) {
		SharedPreferences sharedPreferences = activity.getSharedPreferences(
				HctConstants.PASSWORD_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		Editor editor = sharedPreferences.edit();

		editor.putString(HctConstants.PASSWORD_STORE_KEY_VALUE, password);
		editor.commit();
	}
	/**
	 * 
	 * @param activity
	 * @return
	 */
	public static String getPassword(Activity activity) {
		SharedPreferences sharedPreferences = activity.getSharedPreferences(
				HctConstants.PASSWORD_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		String password = sharedPreferences.getString(
				HctConstants.PASSWORD_STORE_KEY_VALUE, "");
		return password;
	}
}
